//
//  LHLoginController.swift
//  LHWeiBo
//
//  Created by snowimba on 16/1/19.
//  Copyright © 2016年 snowimba. All rights reserved.
//

import UIKit
import SVProgressHUD

class LHLoginController: UIViewController {
    
    
	let CLIENT_ID = 3840079650
	
	let REDIRECT_URI = "http://www.itheima.com"
	
	let CLIENT_SECRET = "2a3afc1ac325748b5c291c7112d74373"
	
	var type : String?
	
//	var parametersBlack : ((parameters : [String: AnyObject]) -> ())?
	
	lazy var loginView : UIWebView = {
		
		let web = UIWebView()
		
		web.delegate = self
		
		return web
	}()
	
	override func loadView() {
		
		view = loginView
	}
	
//    s://api.weibo.com/oauth2/authorize?client_id=3840079650&redirect_uri=http://www.baidu.com
	
	override func viewDidLoad() {
		super.viewDidLoad()
		
		type == "reg" ? regRequest(): getToken()
		
		setupUI()
		
//		getToken()
		// Do any additional setup after loading the view.
	}
	
	func regRequest() {
		
		let URLString : String = "http://m.weibo.cn/reg/index?jp=1&wm=4406&appsrc=6c0kIG&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D3840079650%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.itheima.com%26from%3D%26with_cookie%3D"
		
		let request : NSURLRequest = NSURLRequest(URL: NSURL(string: URLString)!)
		
		loginView.loadRequest(request)
	}
	
	func setupUI() {
		
		navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: "pop")
		
		navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "read")
	}
	
	func getToken() {
		
		let URLString : String = "https://api.weibo.com/oauth2/authorize?client_id=\(CLIENT_ID)&redirect_uri=\(REDIRECT_URI)"
		
		let request : NSURLRequest = NSURLRequest(URL: NSURL(string: URLString)!)
		
		loginView.loadRequest(request)
	}
	
	func pop() {
		
		dismissViewControllerAnimated(true, completion: nil)
	}
	func read() {
		
		let scriptString = "document.getElementById('userId').value='w8899308@163.com';document.getElementById('passwd').value='8899308'"
//		let scriptString = "document.getElementById('userId').value='yohtr35601@163.com';document.getElementById('passwd').value='qw1987'"
        
//        "document.getElementById('userId').value='yohtr35601@163.com';document.getElementById('passwd').value='qw1987'"
        
        
		
		loginView.stringByEvaluatingJavaScriptFromString(scriptString)
	}
	
	override func viewWillDisappear(animated: Bool) {
		
		SVProgressHUD.dismiss()
	}
}

extension LHLoginController : UIWebViewDelegate {
	
	func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
		
		if let code: String = request.URL?.absoluteString {
			
			if code.hasPrefix("http://www.itheima.com") {
				var index = 0
				for ch in code.characters {
					index++
					if ch == "=" {
						break
					}
				}
				
				let startIndex = code.startIndex.advancedBy(index)
				let endIndex = code.endIndex.advancedBy(0)
				
				let str = code.substringWithRange(startIndex..<endIndex)
				
				let parametersNew : [String: AnyObject] = ["client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "grant_type": "authorization_code", "code": str, "redirect_uri": REDIRECT_URI]
				
				LHLoginAboutViewModel.sharedViewModel.requestModelData(parametersNew, finshBlack: { (isFalse) -> () in
						
						if isFalse {
                            
                            self.dismissViewControllerAnimated(false ,completion: { () -> Void in
                                
                                NSNotificationCenter.defaultCenter().postNotificationName("changeRootVC", object: self)
                                
                            })
                        }else{
                    
                            SVProgressHUD.showErrorWithStatus("请求失败!")
                    }
                    
                    
					})
				
//				pop()
				return false
			}
		}
		return true
	}
	
	func webViewDidStartLoad(webView: UIWebView) {
		
		SVProgressHUD.show()
	}
    
	func webViewDidFinishLoad(webView: UIWebView) {
		SVProgressHUD.dismiss()
//		print(loginView.request?.URL?.absoluteString)
		
//        a889930808@126.com
	}
}
